package com.totoro.controller.request;

import com.totoro.pojo.*;
import com.totoro.service.EvaluationService;
import com.totoro.service.ProductService;
import com.totoro.service.SellerService;
import com.totoro.service.ShopService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author TOTORO
 * @date 2021/7/15 19:23
 */
@Controller
@RequestMapping("/shop")
public class ShopRequestController {

    @Autowired
    ShopService shopService;
    @Autowired
    EvaluationService evaluationService;
    @Autowired
    SellerService sellerService;
    @Autowired
    private ProductService productService;

    @SneakyThrows
    @RequestMapping("/view_shop")
    public String goShopIndex(@RequestParam(value = "brandId", required = false, defaultValue = "0") Integer brandId, Model model, HttpSession session){
        if(brandId == 0){
            String configCode= URLEncoder.encode("系统繁忙，请稍后再试","UTF-8");
            return "redirect:/tmall_process_error.htm?errorType=NOT&errorMsg="+configCode;
        }
        // 增加一条店铺访问记录
        // 必须登录了才算访问记录
        User user = (User) session.getAttribute("user");
        if(null != user){
            Seller seller = sellerService.findSellerIdByUserId(user.getUserId());
            if(seller == null){
                shopService.addShopAccess(brandId);
            } else{
                // 如果卖家自己一直进入自己店铺，不算
                Shop shop = shopService.findShopBySlid(seller.getId());
                if(shop.getId() != brandId){
                    shopService.addShopAccess(brandId);
                }
            }
        }
        Shop oneShop = shopService.findAllProduct(brandId, 0, 28);
        if(null == oneShop){
            String configCode= URLEncoder.encode("没有找到或不存在该店铺!","UTF-8");
            return "redirect:/tmall_process_error.htm?errorType=NOT&errorMsg="+configCode;
        }
        Shop twoShop = shopService.findAllProduct(brandId, 28, 24);
        model.addAttribute("shop", oneShop);
        List<ShopCategory> shopCategories = shopService.findAllShopCategory(oneShop.getId());
        // 键值对通过类别id拿分类
        Map<String, ShopCategory> map = new HashMap<>(shopCategories.size());
        for (ShopCategory shopCategory : shopCategories) {
            map.put(shopCategory.getId()+"", shopCategory);
        }
        model.addAttribute("allCategory", map);
        model.addAttribute("twoShopProducts", twoShop);
        model.addAttribute("oneShopProducts", oneShop);
        // 将获得销量排行和收藏排行的商品们
        List<Product> dealDescProducts = shopService.findTermDescProduct(brandId, "t2.deal_count desc");
        List<Product> collectDescProducts = shopService.findTermDescProduct(brandId, "t2.collect_count desc");
        model.addAttribute("dealDescProducts", dealDescProducts);
        model.addAttribute("collectDescProducts", collectDescProducts);

        saveShopInfo(model, oneShop);
        // 获得所有店铺轮播图
        List<ShopSwitchImage> shopSwitchImages = shopService.findShopSwitchImage(oneShop.getId(), null);
        model.addAttribute("shopSwitchImages", shopSwitchImages);
        return "include/shop/shop";
    }

    @SneakyThrows
    @RequestMapping("/category")
    public String goShopCategory(@RequestParam(value = "brandId", required = false, defaultValue = "0") Integer brandId,
                                 @RequestParam(value = "keyWord", required = false, defaultValue = "") String keyWord,
                                 @RequestParam(value = "shopCategory", required = false, defaultValue = "0") int scid,
                                 @RequestParam(value = "orderType", required = false, defaultValue = "") String orderType,
                                 @RequestParam(value = "lowPrice", required = false , defaultValue = "0") double lowPrice,
                                 @RequestParam(value = "highPrice", required = false, defaultValue = "9999999") double highPrice,
                                 @RequestParam(value = "curr", required = false, defaultValue = "1") int curr,
                                 Model model){
        if(brandId == 0){
            String configCode= URLEncoder.encode("系统繁忙，请稍后再试","UTF-8");
            return "redirect:/tmall_process_error.htm?errorType=NOT&errorMsg="+configCode;
        }
        Shop shop = shopService.findAllProduct(brandId, 0, 28);
        if(null == shop){
            String configCode= URLEncoder.encode("没有找到或不存在该店铺!","UTF-8");
            return "redirect:/tmall_process_error.htm?errorType=NOT&errorMsg="+configCode;
        }
        model.addAttribute("shop", shop);
        List<ShopCategory> allCategory = shopService.findAllShopCategory(shop.getId());
        // 键值对通过类别id拿分类
        Map<String, ShopCategory> map = new HashMap<>();
        for (ShopCategory shopCategory : allCategory) {
            map.put(shopCategory.getId()+"", shopCategory);
        }
        model.addAttribute("allCategory", map);

        // 将获得销量排行和收藏排行的商品们
        List<Product> dealDescProducts = shopService.findTermDescProduct(brandId, "t2.deal_count desc");
        List<Product> collectDescProducts = shopService.findTermDescProduct(brandId, "t2.collect_count desc");
        model.addAttribute("dealDescProducts", dealDescProducts);
        model.addAttribute("collectDescProducts", collectDescProducts);

        String descSql = "t1.create_time";
        // 用户选择的排序方式
        switch (orderType){
            case "hotsell_desc":
                descSql = "t2.deal_count desc";
                break;
            case "newOn_desc":
                descSql = "t2.create_time desc";
                break;
            case "hotkeep_desc":
                descSql = "t2.collect_count desc";
                break;
            case "price_asc":
                descSql = "t2.product_now_price asc";
                break;
            case "price_desc":
                descSql = "t2.product_now_price desc";
                break;
        }

        // 拿到真实的分类商品
        List<Product>  products = shopService.findAllShopCategoryAndProduct(scid, keyWord, descSql, lowPrice, highPrice, curr);
        for (int i = 0; i < products.size(); i++) {
            System.out.println(products.get(i).getId());
        }
        model.addAttribute("products", products);
        model.addAttribute("pageType", "category");
        int allCount = shopService.findAllShopCategoryAndProduct(scid ,keyWord, descSql, lowPrice, highPrice, 0).size();
        model.addAttribute("allCount", allCount);

        // 获得本店铺好评商品
        List<Product> goodProducts = productService.findShopOtherProducts(brandId, 0, 10);
        model.addAttribute("goodProducts", goodProducts);

        saveShopInfo(model, shop);
        return "include/shop/shop_category";
    }

    @SneakyThrows
    @RequestMapping("/search")
    public String search(@RequestParam(value = "brandId", required = false, defaultValue = "0") Integer sid, @RequestParam(value = "keyWord", required = false, defaultValue = "") String keyWord,
                         @RequestParam(value = "orderType", required = false, defaultValue = "") String orderType,
                         @RequestParam(value = "lowPrice", required = false , defaultValue = "0") double lowPrice,
                         @RequestParam(value = "highPrice", required = false, defaultValue = "9999999") double highPrice,
                         @RequestParam(value = "curr",required = false, defaultValue = "1") int curr,
                         Model model){
        if(sid == 0){
            String configCode= URLEncoder.encode("系统繁忙，请稍后再试","UTF-8");
            return "redirect:/tmall_process_error.htm?errorType=NOT&errorMsg="+configCode;
        }
        Shop shop = shopService.findShopBySid(sid);
        if(null == shop){
            String configCode= URLEncoder.encode("没有找到或不存在该店铺!","UTF-8");
            return "redirect:/tmall_process_error.htm?errorType=NOT&errorMsg="+configCode;
        }
        model.addAttribute("shop", shop);

        List<ShopCategory> allCategory = shopService.findAllShopCategory(shop.getId());
        // 键值对通过类别id拿分类
        Map<String, ShopCategory> map = new HashMap<>();
        for (ShopCategory shopCategory : allCategory) {
            map.put(shopCategory.getId()+"", shopCategory);
        }
        model.addAttribute("allCategory", map);

        // 将获得销量排行和收藏排行的商品们
        List<Product> dealDescProducts = shopService.findTermDescProduct(sid, "t2.deal_count desc");
        List<Product> collectDescProducts = shopService.findTermDescProduct(sid, "t2.collect_count desc");
        model.addAttribute("dealDescProducts", dealDescProducts);
        model.addAttribute("collectDescProducts", collectDescProducts);

        String descSql = "t1.create_time";
        // 用户选择的排序方式
        switch (orderType){
            case "hotsell_desc":
                descSql = "t2.deal_count desc";
                break;
            case "newOn_desc":
                descSql = "t2.create_time desc";
                break;
            case "hotkeep_desc":
                descSql = "t2.collect_count desc";
                break;
            case "price_asc":
                descSql = "t2.product_now_price asc";
                break;
            case "price_desc":
                descSql = "t2.product_now_price desc";
                break;
        }
        List<Product> products = shopService.keywordSearchShopProduct(sid, keyWord, descSql, lowPrice, highPrice, curr);
        model.addAttribute("products", products);
        // 区分分类和搜索
        model.addAttribute("pageType", "search");
        // 查一遍未分页的，用作总页数
        int allCount = shopService.keywordSearchShopProduct(sid, keyWord, descSql, lowPrice, highPrice, 0).size();
        model.addAttribute("allCount", allCount);

        // 获得本店铺好评商品
        List<Product> goodProducts = productService.findShopOtherProducts(sid, 0, 10);
        model.addAttribute("goodProducts", goodProducts);

        saveShopInfo(model, shop);
        return "include/shop/search_baby";
//        return "include/shop/contain/search_and_category";
    }

    void saveShopInfo(Model model, Shop shop){
        SuperEvaluationFind superEvaluationFind = new SuperEvaluationFind();
        superEvaluationFind.setSlid(1);
        int allEvaluation = evaluationService.findUserAllEvaluationBySlid(superEvaluationFind).size();
        // 计算卖家分，宝贝分，物流分 （总分除评价数）
        double sellerStar = Double.parseDouble(String.format("%.2f", (double)shop.getShopSellerStar() / allEvaluation));
        double babyStar = Double.parseDouble(String.format("%.2f", (double)shop.getShopBabyStar() / allEvaluation));
        double logisticsStar = Double.parseDouble(String.format("%.2f", (double)shop.getShopLogisticsStar() / allEvaluation));
        model.addAttribute("sellerStar", sellerStar);
        model.addAttribute("babyStar", babyStar);
        model.addAttribute("logisticsStar", logisticsStar);
        // 获得同行最高分
        Shop otherMaxShop = shopService.findOtherMaxScore(shop.getId());
        // 计算自己与同行的平均分差距
        // 获得同行最高的评论数
        int otherMaxProductComments = evaluationService.findUserAllEvaluationBySlid(new SuperEvaluationFind(otherMaxShop.getSlid())).size();
        double otherMaxSellerStar =  Double.parseDouble(String.format("%.2f", (double)otherMaxShop.getShopSellerStar() / otherMaxProductComments));
        double otherMaxBabyStar = Double.parseDouble(String.format("%.2f", (double)otherMaxShop.getShopBabyStar() / otherMaxProductComments));
        double otherMaxLogisticsStar = Double.parseDouble(String.format("%.2f", (double)otherMaxShop.getShopLogisticsStar() / otherMaxProductComments));
        model.addAttribute("gapSellerStar", Double.parseDouble(String.format("%.2f", (double)sellerStar - otherMaxSellerStar)));
        model.addAttribute("gapBabyStar", Double.parseDouble(String.format("%.2f", (double)babyStar - otherMaxBabyStar)));
        model.addAttribute("gapLogisticsStar", Double.parseDouble(String.format("%.2f", (double)logisticsStar - otherMaxLogisticsStar)));
    }

}
